package com.hmdp.utils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    private static final long BEGIN_TIMESTAMP=1689811200;
    /**
     * 序列号的位数
     */
    private static final int COUNT_BITS=32;

    private StringRedisTemplate  stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate){//可以使用构造函数来注入，也可以直接用    @Resource
        this.stringRedisTemplate=stringRedisTemplate;
    }
    public long nextId(String keyPrefix){//这个传入的是别名，就是用于区别缓存名
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        //2.生成序列号
        //2.1 获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        //2.2自增长
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        //3.拼接返回


        return timestamp<<COUNT_BITS | count;//把COUNT_BITS时间戳往前面移动32位，后面的用count去插入。|代表的意思是，你count插入的一定成功
    }

/**
 * 这个用来生成时间戳到目标年月日时分秒过的秒数。1689811200
 */
 /*   public static void main(String[] args) {//这个用来生成时间戳到当前年月日时分秒过的秒数。
        LocalDateTime time =LocalDateTime.of(2023,7,20,0,0,0);
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(second);
    }*/
}
